﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class EnemyAIAvoid : MonoBehaviour {
    public Transform eyes;
    public IJoyStick joyStick;

    //大于这个距离则视为没有碰到
    private float _hitRange = 0.4f;

    //记录上一次正前方碰撞到的物体
    private GameObject _lastHitObject;
    //在刚触碰到_lastHitObject的时候，记录该时间
    private System.DateTime _lastHitObjectTime;

    void Start () {
		
	}
	
	void Update () {
        Debug.DrawRay(eyes.position, eyes.forward * _hitRange, Color.red);

        System.DateTime curTime = System.DateTime.Now;

        RaycastHit hit;
        if (Physics.Raycast(eyes.position, eyes.forward, out hit, _hitRange))
        {
            //正前方触碰到的障碍物与上一帧触碰到的是同一个
            if (_lastHitObject != null
                && _lastHitObject == hit.collider.gameObject)
            {
                double duration = (curTime - _lastHitObjectTime).TotalSeconds;
                if (duration > 1f)
                {
                    //注意，这里不是立即起效，转向是发生在下一次tank移动相关的脚本中
                    TurnToAnotherDirection(joyStick);

                    //把记录清空，可以起到隔一帧再判断的作用，因为要先让转向起效后再继续判断
                    _lastHitObject = null;

                    //Debug.Log("hit same object duration=" + duration);
                }
            }
            else
            {
                _lastHitObject = hit.collider.gameObject;
                _lastHitObjectTime = curTime;
            }
        }
        else
        {
            _lastHitObject = null;
        }
    }

    private void TurnToAnotherDirection(IJoyStick joyStick)
    {
        int turnTimes = Random.Range(1, 4);
        //Debug.Log("random turn=" + turnTimes);
        for (int i = 0; i < turnTimes; i++)
        {
            joyStick.TurnCoarseDirClockWise();
        }
    }
}
